package service

import (
	"backend/api"
	"backend/config"
	"backend/global"
	"backend/internal/biz"
	"backend/internal/models"
	"backend/pkg/utils"
	"context"
	"path/filepath"

	"github.com/gin-gonic/gin"

	"go.uber.org/zap"
)

type MediaRepo interface {
	Create(ctx context.Context, media []*models.Media) ([]*biz.Media, error)
	FindByID(ctx context.Context, id uint64) (*biz.Media, error)
	DeleteByID(ctx context.Context, id uint64) error
	DeleteCacheByID(ctx context.Context, id uint64) error
}

type MediaService struct {
	repo MediaRepo
	log  *zap.Logger
	conf *config.Configuration
}

func NewMediaService(repo MediaRepo, log *zap.Logger) *MediaService {
	return &MediaService{repo: repo, log: log}
}

func (s *MediaService) Save(ctx *gin.Context, params *api.UploadRequest) (*biz.Media, error) {

	perfix := utils.GetPrefix(params.Type, s.conf)
	if perfix == "" {
		return nil, global.BadRequest("文件类型错误")
	}
	rootDir := utils.RootPath()
	staticPath := utils.GetStoragePath(params.Type)
	if staticPath == "" {
		return nil, global.BadRequest("文件类型错误")
	}
	uploadPath := filepath.Join(rootDir, staticPath)
	err := ctx.SaveUploadedFile(params.File, uploadPath+params.FileName)
	if err != nil {
		return nil, global.BadRequest("文件上传失败")
	}
	return &biz.Media{
		URL:  perfix + params.FileName,
		Type: params.Type,
	}, nil

}
